package com.hoopchina.ui.main;

import com.hoopchina.data.ListBaseAdapter;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.database.DataSetObserver;

/**UnrolledListView
 * 自定义listview
 * 
 * @author Neusoft
 */
public class UnrolledListView extends LinearLayout implements IListViewDataObserver {
	
	private class CustomDataSetObserver extends DataSetObserver {
		private IListViewDataObserver mObserver;
		public CustomDataSetObserver( IListViewDataObserver aObserver ) {
			mObserver = aObserver;
		}
		
		@Override
		public void onChanged() {
			super.onChanged();
			mObserver.onChanged();
		}
	}
	
	private ListBaseAdapter        _adapter;              // data adapter
	private CustomDataSetObserver  _dataObserver;
	
	/**
	 *  构造器
	 */
	public UnrolledListView(Context context) {
		super(context);
		_dataObserver = new CustomDataSetObserver( this );
	}
	
	/**
	 * 构造器	
	 */
	public UnrolledListView(Context context, AttributeSet set) {
		super(context, set);
		_dataObserver = new CustomDataSetObserver( this );
	}
	
	/**
	 * 把Adapter中的view循环放到当前控件里
	 */
	private void populateList() {
		if ( _adapter == null ) {
			return;
		}
		if( getChildCount() > 0 ) {
			removeAllViews();
		}
		int count = _adapter.getCount();
		for( int i = 0; i < count; ++i ) {
			View view = _adapter.getView( i, null, null );
			if ( view != null ) {
				addView( view, i );
			}
		}
	}
	
	/**
	 * 获得当前控件用到的适配器
	 */
	public BaseAdapter getAdapter() {
		return _adapter;
	}
	
	/**
	 * 设置当前组件的适配器
	 */
	public void setAdapter( ListBaseAdapter aAdapter ) {
		_adapter = aAdapter;
		_adapter.registerDataSetObserver( _dataObserver );
		populateList();
	}

	@Override
	public void onChanged() {
		populateList();
	}

}
